package approve.action;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import model.pojo.Employee;
import model.pojo.Languages;
import models.util.UtilInitLang;
import nguyen.dao.LoginSystem;
import nguyen.dao.ReceiverDocumentDAO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import approval.dao.AcEliManagerDAO;
import approval.dao.LangDAO;


public class LoginActivity extends Activity {
	class PInfo {
		private String appname = "";
		private String pname = "";
		private String versionName = "";
		private int versionCode = 0;
	}
	EditText username;
	EditText pass,dbname;
//	Spinner spLangs;
	private Bundle alllangs = new Bundle();
	String typeLang = "EN",database="" ;
	UtilInitLang utilang = new UtilInitLang();
	private boolean read = true;
	ImageView imageVN,imageEN,imageKR;
	AcEliManagerDAO acelidao= new AcEliManagerDAO();
	
	//TODO hongmophi
	private String userName,password,dbn;
	Employee emp;
	private int SIMPLE_NOTFICATION_ID;
	
	//auto update
	public int VersionCode;
	public String VersionName="";
	public String ApkName ;
	public String AppName ;
	public String BuildVersionPath="";
	public String urlpath ;
	public String PackageName;
	public String InstallAppPackageName;
	public String Text="";
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Text= "New".toString();

		
		ApkName = "AndroidApproval.apk";//"Test1.apk";// //"DownLoadOnSDcard_01.apk"; //      
		AppName="AndroidApproval";
		BuildVersionPath = "http://14.63.215.15/approval_version.txt".toString();
		PackageName = "package:com.SelfInstall01".toString(); //"package:com.Test1".toString();
		urlpath = "http://14.63.215.15/" + ApkName.toString();


		GetVersionFromServer(BuildVersionPath); 
		
		readFile();
		

		if(checkInstalledApp(AppName.toString()) == true)
		{   
			Toast.makeText(getApplicationContext(), this.getAlllangs().getBundle(typeLang).getString("appfound")+" " + AppName.toString(), Toast.LENGTH_SHORT).show();


		}else{
			Toast.makeText(getApplicationContext(), this.getAlllangs().getBundle(typeLang).getString("appnotfound")+" "+ AppName.toString(), Toast.LENGTH_SHORT).show();          

		}
		
		
		setContentView(R.layout.login);
		initAttribute();
//		initLang();
		Button btLogin = (Button) findViewById(R.id.btLogin);
		username = (EditText) findViewById(R.id.userName);
		pass = (EditText) findViewById(R.id.pass);
		dbname=(EditText)findViewById(R.id.tv_dbname);
//		btLogin.setOnClickListener(loginbtn);

		
		imageVN = (ImageView)findViewById(R.id.imageViewVN);
		imageEN = (ImageView)findViewById(R.id.imageViewUK);
		imageKR = (ImageView)findViewById(R.id.imageViewKR);
		
		imageVN.setOnClickListener(processImageVN);
		imageEN.setOnClickListener(processImageEN);
		imageKR.setOnClickListener(processImageKR);
		
		// TODO hongmophi
		
	
		
		if(!username.getText().toString().equals("") && !pass.getText().toString().equals("") && !dbname.getText().toString().equals("")){
			
			if(acelidao.checkexitdb(dbname.getText().toString())==true){
				database=dbname.getText().toString();
				System.out.println(database);
				
				emp = checkLogin(username.getText().toString(), pass.getText().toString());
				if (emp != null) {
					startActivity(emp);
					//showNotificationMessage();
				} 
				else {
					openDialogError();
				}
				
				
			}else{
				openDialogNoDB();
			}
			
			
		}
		else{
			btLogin.setOnClickListener(loginbtn);
		}
		
		final CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.checkRemember);
		rememberMeCbx.setOnClickListener(new OnClickListener() {
			
			
			public void onClick(View v) {
				 if (((CheckBox) v).isChecked()) {
					 System.out.println(" boolean check : " + ((CheckBox) v).isChecked());
					 try {
					 userName = username.getText().toString();
					 password = pass.getText().toString();
					 dbn=dbname.getText().toString();
					 if(!username.equals("") && !password.equals("")){
						 System.out.println("Last username :" + userName);
						 System.out.println("Last password : " + password);
//						 	File f = new File("user.txt");
							FileOutputStream file = openFileOutput("user.txt", Context.MODE_PRIVATE);
							file.write(dbn.getBytes());
							file.write("-".getBytes());
							file.write(userName.getBytes());
							file.write("-".getBytes());
							MessageDigest ms = MessageDigest.getInstance("MD5");
							byte[] enpas =ms.digest(password.getBytes());
							file.write(password.getBytes());
							file.close();
					 }
						} catch (NoSuchAlgorithmException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					 
				 }else{
					 System.out.println("Not check remember ++++++++++++++++++++++++++++++");
				 }
			}
		});
	}
	private OnClickListener loginbtn = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
//			Employee emp = checkLogin(username.getText().toString(), pass.getText().toString());
			if(acelidao.checkexitdb(dbname.getText().toString())==true){
				database=dbname.getText().toString();
				
				emp = checkLogin(username.getText().toString(), pass.getText().toString());
				if (emp != null) {
					startActivity(emp);
					//showNotificationMessage();
				} else {
					openDialogError();
				}
			}else{
				openDialogNoDB();
			}
			
		}
	}; 
	
	private void startActivity(Employee em) {
		Intent i = new Intent(this, MainFrame.class);		
		i.putExtra("database", getDatabase());
		i.putExtra("lang", typeLang);
		i.putExtras(alllangs);
		i.putExtra("em", em);
		startActivity(i);
	}
	private void openDialogError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		Bundle lang = this.getAlllangs().getBundle(typeLang);
		builder.setTitle("Warning");
		builder.setMessage(lang.getString("ac_tb_UserOrPassNotCorrect"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.show();
	}
	
	private void openDialogNoDB() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		Bundle lang = this.getAlllangs().getBundle(typeLang);
		builder.setTitle("Warning");
		builder.setMessage(lang.getString("ac_CSDLKhongTonTai"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.show();
	}
	
	public void setDatabase(String database) {
		this.database = database;
	}
	public Employee checkLogin(String username, String pass) {
		LoginSystem lg = new LoginSystem();
		Employee emp = lg.checkLogin(username, pass,getDatabase());
		return emp;
	}
	public String getDatabase() {
		//Bundle extras = getIntent().getExtras();
		//database = extras.getString("database");
		return database;
	}
	public void initAttribute() {
		Bundle lang = this.getAlllangs().getBundle(typeLang);
		TextView lbdbname=(TextView) findViewById(R.id.lb_dbname);
		lbdbname.setText(lang.getString("ac_ma_DatabaseName"));
		TextView t = (TextView) findViewById(R.id.tendn);
		t.setText(lang.getString("ac_ma_UserName"));
		TextView t2 = (TextView) findViewById(R.id.matkhau);
		t2.setText(lang.getString("ac_ma_Password"));
		Button bt = (Button) findViewById(R.id.btLogin);
		bt.setText(lang.getString("ac_login"));
	}
//	private void initLang() {
//		String[] langs = new String[] { "Viet Nam", "English", "Korea" };
//		ArrayAdapter<String> arr = new ArrayAdapter<String>(this,
//				android.R.layout.simple_spinner_dropdown_item, langs);
////		ArrayAdapter<LanguageAdapter> arr = new ArrayAdapter<LanguageAdapter>(this,android.R.layout.simple_spinner_dropdown_item);
//		spLangs = (Spinner) findViewById(R.id.cbLang);
//		spLangs.setAdapter(arr);
//		spLangs.setOnItemSelectedListener(spTypeEvent);
//	}
//	private OnItemSelectedListener spTypeEvent = new OnItemSelectedListener() {
//		public void onItemSelected(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//			if (arg2 == 0)
//				typeLang = "VN";
//			if (arg2 == 1)
//				typeLang = "EN";
//			if (arg2 == 2)
//				typeLang = "KR";
//			Log.d(getApplicationContext().getPackageName(), "Select Item :"
//					+ typeLang);
//			initAttribute();
//		}

//		public void onNothingSelected(AdapterView<?> arg0) {
//			// TODO Auto-generated method stub
//			Log.d(getApplicationContext().getPackageName(), "Select Item :"
//					+ "Nothing");
//			typeLang = "EN";
//		};
//	};
	public Bundle getAlllangs() {
		if (isRead()) {
			LangDAO lang = new LangDAO();
			Bundle resultVN = new Bundle();
			Bundle resultEN = new Bundle();
			Bundle resultKR = new Bundle();
			try {
				ArrayList<Languages> arr = lang.allLang();
				for (int i = 0; i < arr.size(); i++) {
						resultVN.putString(arr.get(i).getId(), arr.get(i).getVn());
						resultEN.putString(arr.get(i).getId(), arr.get(i).getEn());
						resultKR.putString(arr.get(i).getId(), arr.get(i).getKr());
					};

			} catch (Exception E) {
				E.printStackTrace();
			}
			alllangs.putBundle("VN", resultVN);
			alllangs.putBundle("EN", resultEN);
			alllangs.putBundle("KR", resultKR);
		}
		setRead(false);
		return alllangs;
	}
	public boolean isRead() {
		return read;
	}
	public void setRead(boolean read) {
		this.read = read;
	}
	
	// image language
	public OnClickListener processImageVN = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			typeLang = "VN";
			initAttribute();
		}
	};
	
	public OnClickListener processImageEN = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			typeLang = "EN";
			initAttribute();
		}
	};
	
	public OnClickListener processImageKR = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			typeLang = "KR";
			initAttribute();
		}
	};
	
	
	
	// TODO hongmophi
	private void readFile(){
		
		try {
			FileInputStream fr = openFileInput("user.txt");
			Scanner scanner = new Scanner(fr);
			scanner.useDelimiter("-");
			dbname.setText(scanner.next().trim());
			username.setText(scanner.next().trim());
			pass.setText(scanner.next().trim());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	ReceiverDocumentDAO rd = new ReceiverDocumentDAO();
	private void showNotificationMessage(){
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		final Notification notifyDetails;
		int count=rd.countAllNewMessage(emp.getIdemployee(), getDatabase());
		if(count ==0 || count==1){
		
		notifyDetails = new Notification(R.drawable.ic_launcher,
				count + " new message", 1000);
		}
		else{
			notifyDetails = new Notification(R.drawable.ic_launcher,
					count + " new messages", 1000);
		}
//		long[] vibrate = { 500, 600, 200, 300 };
//		notifyDetails.vibrate = vibrate;
		notifyDetails.defaults = Notification.DEFAULT_ALL;
		Context context = getApplicationContext();
		CharSequence contentTitle = "Schogini Systems. Simple Notification";
		CharSequence contentText = "Get back to Application on clicking me";

		Intent notifyIntent = new Intent(context, LoginActivity.class);

		PendingIntent intent = PendingIntent.getActivity(LoginActivity.this,
				0, notifyIntent,
				android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

		notifyDetails.setLatestEventInfo(context, contentTitle,
				contentText, intent);

		mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
				notifyDetails);
		mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
		
	}
//	private class mainTask extends TimerTask {
//
//		@Override
//		public void run() {
//			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
//			final Notification notifyDetails;
//			if(ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) ==0 || ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase())==1){
//			
//			notifyDetails = new Notification(R.drawable.ic_launcher,
//					ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) + " new message", 1000);
//			}
//			else{
//				notifyDetails = new Notification(R.drawable.ic_launcher,
//						ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) + " new messages", 1000);
//			}
////			long[] vibrate = { 500, 600, 200, 300 };
////			notifyDetails.vibrate = vibrate;
//			notifyDetails.defaults = Notification.DEFAULT_ALL;
//			Context context = getApplicationContext();
//			CharSequence contentTitle = "Schogini Systems. Simple Notification";
//			CharSequence contentText = "Get back to Application on clicking me";
//
//			Intent notifyIntent = new Intent(context, LoginActivity.class);
//
//			PendingIntent intent = PendingIntent.getActivity(LoginActivity.this,
//					0, notifyIntent,
//					android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
//
//			notifyDetails.setLatestEventInfo(context, contentTitle,
//					contentText, intent);
//
//			mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
//					notifyDetails);
//			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
//			
//		}
//		
//	}
	
	private Boolean checkInstalledApp(String appName){
		return getPackages(appName);    
	}
	
	// Get Information about Only Specific application which is Install on Device.
	public String getInstallPackageVersionInfo(String appName) 
	{
		String InstallVersion = "";     
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		final int max = apps.size();
		for (int i=0; i<max; i++) 
		{
			//apps.get(i).prettyPrint();  
			
			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
//				InstallVersion = "Install Version Code: "+ apps.get(i).versionCode+
//				" Version Name: "+ apps.get(i).versionName.toString();
				InstallVersion = apps.get(i).versionName.toString();
				break;
			}
		}
Toast.makeText(getApplicationContext(), this.getAlllangs().getBundle(typeLang).getString("currenversion")+" : " + InstallVersion.toString(), Toast.LENGTH_LONG).show();
		
		return InstallVersion.toString();
	}
	private Boolean getPackages(String appName) 
	{
		Boolean isInstalled = false;
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		int max = apps.size();
		System.out.println(max);
		for (int i=0; i<max; i++) 
		{
			//apps.get(i).prettyPrint();
		
			System.out.println(apps.get(i).appname.toString() + " - " + appName.toString());
		
			
			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				//System.out.println("b2");
				/*if(apps.get(i).versionName.toString().contains(VersionName.toString()) == true &&
                        VersionCode == apps.get(i).versionCode)
                {
                    isInstalled = true;
                    Toast.makeText(getApplicationContext(),
                            "Code Match", Toast.LENGTH_SHORT).show(); 
                    openMyDialog();
                }*/
				if(VersionCode <= apps.get(i).versionCode)
				{
					System.out.println("phien ban moi");
					isInstalled = false;

					/*Toast.makeText(getApplicationContext(),
                            "Install Code is Less.!", Toast.LENGTH_SHORT).show();*/

					/*DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which)
							{
							case DialogInterface.BUTTON_POSITIVE:
								//Yes button clicked
								//SelfInstall01Activity.this.finish(); Close The App.

								DownloadOnSDcard();
								InstallApplication();
								UnInstallApplication(PackageName.toString());

								break;

							case DialogInterface.BUTTON_NEGATIVE:
								//No button clicked

								break;
							}
						}
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("New Apk Available..").setPositiveButton("Yes Proceed", dialogClickListener)
					.setNegativeButton("No.", dialogClickListener).show();*/

				}    
				if(VersionCode > apps.get(i).versionCode)
				{
					System.out.println("phien ban cu");
					isInstalled = true;
					/*Toast.makeText(getApplicationContext(),
                            "Install Code is better.!", Toast.LENGTH_SHORT).show();*/

					DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which)
							{
							case DialogInterface.BUTTON_POSITIVE:
								//Yes button clicked
								//SelfInstall01Activity.this.finish(); Close The App.

								DownloadOnSDcard();
								InstallApplication();
								UnInstallApplication(PackageName.toString());

								break;

							case DialogInterface.BUTTON_NEGATIVE:
								//No button clicked

								break;
							}
						}
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage(this.getAlllangs().getBundle(typeLang).getString("youareusingversion")+" "+getInstallPackageVersionInfo(AppName.toString()).toString()+". "+this.getAlllangs().getBundle(typeLang).getString("nownewversion")
							+ GetVersionFromServer(VersionName.toString()).toString()+ ". "+this.getAlllangs().getBundle(typeLang).getString("doyouwantinstall") +"?")
					.setPositiveButton(this.getAlllangs().getBundle(typeLang).getString("install"), dialogClickListener)
					.setNegativeButton(this.getAlllangs().getBundle(typeLang).getString("cancel"), dialogClickListener).show();              
					
				}
			}
		}

		
		
		
		return isInstalled;
	}
	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) 
	{       
		ArrayList<PInfo> res = new ArrayList<PInfo>();        
		List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);

		for(int i=0;i<packs.size();i++) 
		{
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue ;
			}
			if(p.applicationInfo.loadLabel(getPackageManager()).toString().equals(AppName)){
				PInfo newInfo = new PInfo();
				newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
				newInfo.pname = p.packageName;
				newInfo.versionName = p.versionName;
				newInfo.versionCode = p.versionCode;
				//newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
				///System.out.println(p.applicationInfo.loadLabel(getPackageManager()).toString()+"-"+p.packageName+"-"+p.versionName +" - "+ p.versionCode);
				res.add(newInfo);
			}
		}
		return res; 
	}


	public void UnInstallApplication(String packageName)// Specific package Name Uninstall.
	{
		//Uri packageURI = Uri.parse("package:com.CheckInstallApp");
		Uri packageURI = Uri.parse(packageName.toString());
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent); 
	}
	public void InstallApplication()
	{   
		Uri packageURI = Uri.parse(PackageName.toString());
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);

		//      Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

		//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//intent.setFlags(Intent.ACTION_PACKAGE_REPLACED);

		//intent.setAction(Settings. ACTION_APPLICATION_SETTINGS);

		intent.setDataAndType
		(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"  + ApkName.toString())), "application/vnd.android.package-archive");

		// Not open this Below Line Bcuz...
		////intent.setClass(this, Project02Activity.class); // This Line Call Activity Recursively its dangerous.

		startActivity(intent);  
	}
	public String GetVersionFromServer(String BuildVersionPath)
	{
		//this is the file you want to download from the remote server          
		//path ="http://10.0.2.2:82/Version.txt";
		//this is the name of the local file you will create
		// version.txt contain Version Code = 2; \n Version name = 2.1;             
		URL u;
		try {
			u = new URL(BuildVersionPath.toString());

			HttpURLConnection c = (HttpURLConnection) u.openConnection();           
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect();

			//Toast.makeText(getApplicationContext(), "HttpURLConnection Complete.!", Toast.LENGTH_SHORT).show();  

			InputStream in = c.getInputStream();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024]; //that stops the reading after 1024 chars..
			//in.read(buffer); //  Read from Buffer.
			//baos.write(buffer); // Write Into Buffer.

			int len1 = 0;
			while ( (len1 = in.read(buffer)) != -1 ) 
			{               
				baos.write(buffer,0, len1); // Write Into ByteArrayOutputStream Buffer.
			}

			String temp = "";     
			String s = baos.toString();// baos.toString(); contain Version Code = 2; \n Version name = 2.1;

			for (int i = 0; i < s.length(); i++)
			{               
				i = s.indexOf("=") + 1; 
				while (s.charAt(i) == ' ') // Skip Spaces
				{
					i++; // Move to Next.
				}
				while (s.charAt(i) != ';'&& (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.'))
				{
					temp = temp.toString().concat(Character.toString(s.charAt(i))) ;
					i++;
				}
				//
				s = s.substring(i); // Move to Next to Process.!
				temp = temp + " "; // Separate w.r.t Space Version Code and Version Name.
			}
			String[] fields = temp.split(" ");// Make Array for Version Code and Version Name.

			VersionCode = Integer.parseInt(fields[0].toString());// .ToString() Return String Value.
			VersionName = fields[1].toString();

			System.out.println("Vesiom code _ " + VersionCode);
			System.out.println("Vesion name _ " + VersionName);
			baos.close();
		}
		catch (MalformedURLException e) {
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (IOException e) {           
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
		}
		return VersionName;
		//return true;
	}// Method End.

	// Download On My Mobile SDCard or Emulator.
	public void DownloadOnSDcard()
	{
		try{
			URL url = new URL(urlpath.toString()); // Your given URL.

			HttpURLConnection c = (HttpURLConnection) url.openConnection();
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect(); // Connection Complete here.!

			//Toast.makeText(getApplicationContext(), "HttpURLConnection complete.", Toast.LENGTH_SHORT).show();

			String PATH = Environment.getExternalStorageDirectory() + "/download/";
			File file = new File(PATH); // PATH = /mnt/sdcard/download/
			if (!file.exists()) {
				file.mkdirs();
			}
			File outputFile = new File(file, ApkName.toString());           
			FileOutputStream fos = new FileOutputStream(outputFile);

			//      Toast.makeText(getApplicationContext(), "SD Card Path: " + outputFile.toString(), Toast.LENGTH_SHORT).show();

			InputStream is = c.getInputStream(); // Get from Server and Catch In Input Stream Object.

			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len1); // Write In FileOutputStream.
			}
			fos.close();
			is.close();
			System.out.println("thanh cong");
			//till here, it works fine - .apk is download to my sdcard in download file.
			// So plz Check in DDMS tab and Select your Emualtor.

			//Toast.makeText(getApplicationContext(), "Download Complete on SD Card.!", Toast.LENGTH_SHORT).show();
			//download the APK to sdcard then fire the Intent.
		} 
		catch (IOException e) 
		{
			System.out.println("that bai");
			System.out.println("Error! " +	e.toString());
			Toast.makeText(getApplicationContext(), "Error! " +	e.toString(), Toast.LENGTH_LONG).show();
		}           
	}
}
